﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Register.Trans;
using BranchOfSansar.Sansar.Register;
using System.IO;

namespace BranchOfSansar.Register.CallCenter
{
    public partial class frmBaseCallReg : Form
    {

        protected string TypeCode;
        protected vw_CallRequest Request = null;
        public BranchOfSansar.Sansar.Enquiry.vw_Contracts Contract { get; set; }

        //Шинээр дуудлага орууулах
        public frmBaseCallReg()
        {
            InitializeComponent();
        }


        #region Protected Methods

        /// <summary>
        /// Заавал Request авдаг байгуулагчтай байх ёстой
        /// Засах горимоор дуудах функц
        /// </summary>
        protected void SetEditValue()
        {
            //Request -г байгуулагч дээрээ авсан байх ёстой
            txtContractNo.Text = Request.ContractNo.ToString();
            txtPhone.Text = Request.PhoneNumber;
            Globals.setComboSelectedItem(txtStatus, Request.StatusNo);
            Globals.setComboSelectedItem(txtLevel, Request.LevelNo);

            if (!string.IsNullOrEmpty(Request.Reason1))
                Globals.setComboSelectedItem(txtR1, Request.Reason1);
            if (!string.IsNullOrEmpty(Request.Reason2))
                Globals.setComboSelectedItem(txtR2, Request.Reason2);
            if (!string.IsNullOrEmpty(Request.Reason3))
                Globals.setComboSelectedItem(txtR3, Request.Reason3);
          
            if (!string.IsNullOrEmpty(Request.DistrictCode))
                Globals.setComboSelectedItem(txtSection, Request.DistrictCode);
            if (!string.IsNullOrEmpty(Request.SectionNo))
                Globals.setComboSelectedItem(txtPart, Request.SectionNo);
            if (!string.IsNullOrEmpty(Request.QuarterCode))
                Globals.setComboSelectedItem(txtSection, Request.QuarterCode);

            txtApartNo.Text = Request.ApartNo.ToString();
            txtDoorNo.Text = Request.DoorNo.ToString();

            txtAddition.Text = Request.Addition;
            txtReceivedUser.Text = Request.RecvUser;
            if (Request.UserNoOfDid != null)
                Globals.setComboSelectedItem(txtDidUserNo, Request.UserNoOfDid ?? 0);
            if (Request.UserNoOfClosed != null)
                Globals.setComboSelectedItem(txtClosedUserNo, Request.UserNoOfClosed ?? 0);

            txtReceivedDate.DateTime = Request.DateOfReceived;
            if (Request.DateOfPlaning != null)
                txtDueDate.DateTime = Request.DateOfPlaning ?? DateTime.Now;
            if (Request.DateOfClosed != null)
                txtClosedDate.DateTime = Request.DateOfClosed ?? DateTime.Now;



            btnCreate.Text = "Хадгалах";
            btnCreate.Enabled = false;
            btnComment.Enabled = true;
            btnClose.Enabled = true;
            CommentBind();
        }

        /// <summary>
        /// Заавал байгуулагч дээр нь тавих ёстой
        /// </summary>
        protected void LoadFirstValue()
        {
            this.TypeCode = this.Name.Substring(this.Name.Length - 3, 3);
            txtReceivedUser.Text = Globals.UserName;
            txtReceivedDate.DateTime = DateTime.Now;
            txtDueDate.DateTime = DateTime.Now;
            BranchOfSansar.Sansar.Enquiry.Parameter[] paras;
            
            BranchOfSansar.Sansar.Enquiry.User[] usr;
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                paras = ec.Parameters("(it.GroupCode='CS' OR it.GroupCode='CL' OR it.GroupCode='R1' OR it.GroupCode='R2' OR it.GroupCode='R3' OR it.GroupCode='NW' OR it.GroupCode='CP' OR it.GroupCode='DS') AND it.Status=true ");
                usr = ec.Users("it.PositionNo='E'");
            }
            //Бүртэгсэн хэрэглэгч
            txtDidUserNo.Properties.Items.AddRange(usr
                .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                .ToArray());
            Globals.setComboSelectedItem(txtDidUserNo, 0);

            //Төлөв
            txtStatus.Properties.Items.AddRange(paras
                .Where(w => w.GroupCode == "CS")
                .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                .ToArray());
            Globals.setComboSelectedItem(txtStatus, "NEW");

            //Түвшин
            txtLevel.Properties.Items.AddRange(paras
                .Where(w => w.GroupCode == "CL")
                .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                .ToArray());
            Globals.setComboSelectedItem(txtLevel, "NOR");

            #region Хүсэлт хаасан хэрэглэгч
            if (txtClosedUserNo.ShowToolTips)
            {
                txtClosedUserNo.Properties.Items.AddRange(usr
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtClosedUserNo, 0);
            }
            #endregion

            #region Шалтгаан 1 Дамжуулах бүсээс
            if (txtR1.ShowToolTips)
            {
                txtR1.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R1")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR1.SelectedIndex = 0;
            }
            #endregion

            #region Шалтгаан 2 Хэрэглэгчийн буруутай
            if (txtR2.ShowToolTips)
            {
                txtR2.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R2")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR2.SelectedIndex = 0;
            }
            #endregion

            #region Шалтгаан 3 Бусад
            if (txtR3.ShowToolTips)
            {
                txtR3.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R3")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR3.SelectedIndex = 0;
            }
            #endregion

            #region Дүүрэг
            if (txtDistrict.ShowToolTips)
            {
                using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
                {
                    var dis = ec.DistrictList();
                    txtDistrict.Properties.Items.AddRange(dis
                       .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.DistrictCode, Display = s.Name })
                       .ToArray());
                    txtDistrict.SelectedIndex = 0;
                }
            }
            #endregion

            #region Сүлжээ
            if (txtNetwork.ShowToolTips)
            {
                txtNetwork.Properties.Items.AddRange(paras
                  .Where(w => w.GroupCode == "NW")
                  .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                  .ToArray());
                txtNetwork.SelectedIndex = 0;
            }
            #endregion

            #region Тайлбар
            if (txtDesc.ShowToolTips)
            {
                txtDesc.Properties.Items.AddRange(paras
                  .Where(w => w.GroupCode == "DS")
                  .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                  .ToArray());
                txtDesc.SelectedIndex = 0;
            }
            #endregion

            #region Гомдолын төрөл
            if (txtComplain.ShowToolTips)
            {
                txtComplain.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "CP")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtComplain.SelectedIndex = 0;
            }
            #endregion

            #region Хэсэгийн дугааруудыг оруулах
            if (txtPart.ShowToolTips)
            {
                using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
                {
                    var parts = ec.PartList().ToArray();
                    txtPart.Properties.Items.AddRange(parts
                     .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.PartNo, Display = s.Name })
                     .ToArray());
                    txtPart.SelectedIndex = 0;
                }
            }
            #endregion

            btnCreate.Enabled = false;


        }
        
        /// <summary>
        /// Харилцагчийн мэдээллийг дүүргэх
        /// </summary>
        protected void FillData()
        {
            txtContractNo.Text = this.Contract.ContractNo.ToString();
            txtDescription.Text = string.Format("{2},{3} {0} байр {1} тоот", Contract.ApartNo1, Contract.DoorNo, Contract.CustName, Contract.CustRegister);
        }

        protected void SetContractNo(long cno)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var res = tc.ContractDetail(cno);
                if (res == null)
                {
                    txtDescription.Text = "Гэрээний дугаар буруу";
                    Contract = null;
                    return;
                }
                this.Contract = res;
                FillData();
            }

        }

        protected void SetContractNo(string uname)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var res = tc.ContractDetailByUser(uname);
                if (res == null)
                {
                    txtDescription.Text = "Хэрэглэгчийн дугаар буруу";
                    Contract = null;
                    return;
                }
                this.Contract = res;
                FillData();
            }

        }

        protected CallRequest GetData()
        {

            CallRequest result = new CallRequest()
            {
                Addition = txtAddition.Text,
                CompanyNo = "1", //Интернэт
                DateOfPlaning = txtDueDate.DateTime,
                DateOfReceived = txtReceivedDate.DateTime,
                LevelNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtLevel.SelectedItem).StrValue,
                StatusNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtStatus.SelectedItem).StrValue,
                PhoneNumber = txtPhone.Text,
                ReqTypeNo = TypeCode,
                UserNoOfClosed = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtClosedUserNo.SelectedItem).IntValue,
                UserNoOfDid = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDidUserNo.SelectedItem).IntValue,
                UserNoOfReceived = Globals.UserId,
            };
            
            if (txtR1.SelectedIndex > 0)
                result.Reason1 = txtR1.Text;

            if (txtR2.SelectedIndex > 0)
                result.Reason2 = txtR2.Text;

            if (txtR3.SelectedIndex > 0)
                result.Reason3 = txtR3.Text;

            if (txtDistrict.ShowToolTips && txtDistrict.SelectedItem != null)
                result.DistrictCode = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDistrict.SelectedItem).StrValue;

            if (txtSection.ShowToolTips && txtSection.SelectedItem!=null)
                result.SectionNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtSection.SelectedItem).StrValue;

            if (txtQuarter.ShowToolTips && txtQuarter.SelectedItem != null)
                result.QuarterCode = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtQuarter.SelectedItem).StrValue;

            if (txtPart.ShowToolTips && txtPart.SelectedItem !=null)
                result.PartNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtPart.SelectedItem).IntValue;

            if (!string.IsNullOrEmpty(txtApartNo.Text))
                result.ApartNo = txtApartNo.Text;

            if (!string.IsNullOrEmpty(txtDoorNo.Text))
                result.DoorNo = txtDoorNo.Text;

            if (txtNetwork.ShowToolTips && txtNetwork.SelectedItem != null)
                result.Network = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtNetwork.SelectedItem).StrValue;

            if (txtComplain.ShowToolTips && txtComplain.SelectedItem != null)
                result.ComplaintTypeNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtComplain.SelectedItem).StrValue;

            if (chkEngineer.ShowToolTips)
                result.IsEngineer = chkEngineer.Checked;
            else
                result.IsEngineer = false;

            if (txtDesc.ShowToolTips)
                result.Describe = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDesc.SelectedItem).StrValue;

            //Шууд хаагдсан төлөврүү шилжих
            if (TypeCode.Equals("IRS") || TypeCode.Equals("OTR"))
                result.StatusNo = "CLS";

            if (txtClosedDate.Text != "")
                result.DateOfClosed = txtClosedDate.DateTime;
            if (Contract != null)
            {
                result.ContractNo = Contract.ContractNo;
            }

            return result;
        }

        protected void CommentBind()
        {
            using (RegisterClient reg = new RegisterClient(Globals.Token))
            {
                gridComment.DataSource = reg.CommentList(Request.ReqNo);
            }
        }

        #endregion

        #region Events

        protected void txtContractNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BranchOfSansar.Register.Main.frmContractList frm = new BranchOfSansar.Register.Main.frmContractList(true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.Contract = frm.Contract;
                FillData();
            }
        }

        protected void txtContractNo_KeyUp(object sender, KeyEventArgs e)
        {
            long num;
            if (e.KeyCode == Keys.Enter)
            {
                if (long.TryParse(txtContractNo.Text, out num))
                    SetContractNo(num);
                else
                    SetContractNo(txtContractNo.Text);
            }
        }

        protected void btnTransfers_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (Contract != null)
            {
                frmTransactionList frm = new frmTransactionList(Contract.ContractNo);
                frm.Show();
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            CallRequest value = GetData();

            using (RegisterClient rc = new RegisterClient(Globals.Token))
            {
                Result res;
                if (Request == null)
                {
                    res = rc.AddCallRequest(value);
                }
                else
                {
                    value.ReqNo = Request.ReqNo;
                    res = rc.EditCallRequest(value);
                    btnCreate.Enabled = false;
                }

                if (res.Code != 0)
                    Globals.Warr(res.Message);
                else
                {
                    Globals.Info(res.Message);
                    btnCreate.Enabled = false;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
            }
        }

        protected void Field_EditValueChanged(object sender, EventArgs e)
        {
            btnCreate.Enabled = true;
        }

        protected void btnComment_Click(object sender, EventArgs e)
        {
            frmComment frm = new frmComment(Request.ReqNo);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtStatus.Text = "Хийдэж байгаа";
                CommentBind();
            }
        }

        protected void gridComment_DoubleClick(object sender, EventArgs e)
        {
            if (viewComment.SelectedRowsCount > 0)
            {
                var item = (CommentRow)viewComment.GetRow(viewComment.GetSelectedRows()[0]);
                frmComment frm = new frmComment(item);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    CommentBind();
                }
            }
        }

        private void frmBaseCallReg_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnCreate.Enabled)
            {
                if (Globals.Question("Та өөрчлөлтийг хадгалах уу?") == System.Windows.Forms.DialogResult.Yes)
                {
                    btnCreate_Click(null, null);
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            frmClose frm = new frmClose(Request.ReqNo);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtStatus.Text = "Хаасан";
                CommentBind();
            }
        }

        //Дүүрэг солигдох
        private void txtDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {

                string dis_code = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDistrict.SelectedItem).StrValue;
                //Хороо
                txtQuarter.Properties.Items.AddRange(ec.QuarterList(dis_code)
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.QuarterCode, Display = s.Name })
                    .ToArray());
                txtQuarter.SelectedIndex = txtQuarter.Properties.Items.Count > 0 ? 0 : -1;

                //Хороолол
                txtSection.Properties.Items.AddRange(ec.SectionListByDisctrict(dis_code)
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = (int)s.SectionNo, Display = s.Name })
                    .ToArray());
                txtSection.SelectedIndex = txtSection.Properties.Items.Count > 0 ? 0 : -1;
            }
        }


        #endregion


    }
}
